import axios from 'axios';
import { getToken, getTokenType } from '@/utils/auth';
import { Toast } from 'vant';

//创建一个map存储取消令牌
const cancelTokenMap = new Map();
const manageCancelTokenMap = (url,type,source = null) => {
  const requestUrl = url;
  if(type === 'save'){
    cancelTokenMap.set(requestUrl,source);
  } else if (type === 'cancel'){
    cancelTokenMap.delete(requestUrl);
  }
}
const cancelRequest = (requestUrl) => {
  const source = cancelTokenMap.get(requestUrl);
  console.log('source = ',source);
  if(source !== undefined){
    source('axios cancel request');
  }
}

const service = axios.create({
  withCredentials: true,
  timeout: 50000
})

// 请求拦截
service.interceptors.request.use(
  config => {
    config.headers['Authorization'] = getTokenType() + ' ' + getToken();
    //config.baseURL = process.env.NODE_ENV === 'development' ? process.env.VUE_APP_BASE_API_FNT : localStorage.getItem('baseUrl') + '/factory/v1/jy-api';
    config.baseURL = process.env.NODE_ENV === 'development' ? process.env.VUE_APP_BASE_API_CJ : localStorage.getItem('baseUrl') + '/factory/v1/jy-app';
    if(process.env.NODE_ENV === 'development'){
      config.headers['x-request-wan-access'] = true;
    }
    return config;
  },
  error => {
    return Promise.reject(error);
  }
)

// 响应拦截
service.interceptors.response.use(
  response => {
    manageCancelTokenMap(response.config.url, "cancel");
    return response.data;
  },
  error => {
    return Promise.reject(error);
  }
)

service.$cancelRequest = cancelRequest;
service.$CancelToken = axios.CancelToken;
service.$manageCancelTokenMap = manageCancelTokenMap;
export default service;
